<route lang="json5">
{
  style: {
    navigationBarTitleText: '相册'
  }
}
</route>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { useSupabaseCoupleStore } from '@/store/supabaseCouple'
import { useToast } from 'wot-design-uni'
import dayjs from 'dayjs'
import type { Album } from '@/types/couple'

defineOptions({
  name: 'CoupleAlbum',
})

const coupleStore = useSupabaseCoupleStore()
const { success: showSuccess } = useToast()

const showCreateDialog = ref(false)
const newAlbum = ref<Partial<Album>>({
  title: '',
  description: '',
  coverImage: '',
  photos: [],
})

// 使用 store 中的相册数据
const albums = computed(() => coupleStore.albums)
const totalPhotos = computed(() => coupleStore.totalPhotos)

// 跳转到相册详情
const goToAlbumDetail = (album: Album) => {
  uni.navigateTo({
    url: `/pages/album/detail?id=${album.id}`,
  })
}

// 预览图片
const previewImage = (current: string, urls: string[]) => {
  // 过滤掉可能有权限问题的本地图片，只保留网络图片
  // 但保留头像等静态资源图片的显示
  const validUrls = urls.filter(url => url.startsWith('http'))
  const validCurrent = current.startsWith('http') ? current : validUrls[0]

  if (validUrls.length === 0) {
    showSuccess('暂无可预览的图片')
    return
  }

  uni.previewImage({
    current: validCurrent,
    urls: validUrls,
    fail: (err) => {
      console.error('图片预览失败:', err)
      showSuccess('图片预览失败')
    },
  })
}

// 相册操作
const openAlbumActions = (album: Album) => {
  uni.showActionSheet({
    itemList: ['编辑', '删除', '取消'],
    success: (res) => {
      if (res.tapIndex === 0)
        editAlbum(album)
      else if (res.tapIndex === 1)
        confirmRemoveAlbum(album)
    },
  })
}

const editAlbum = async (album: Album) => {
  // 简单实现：直接修改标题
  uni.showModal({
    title: '编辑相册',
    editable: true,
    placeholderText: album.title,
    success: async ({ confirm, content }) => {
      if (confirm && content) {
        await coupleStore.updateAlbum(album.id, { title: content })
        showSuccess('相册已更新')
      }
    },
  })
}

const confirmRemoveAlbum = (album: Album) => {
  uni.showModal({
    title: '删除确认',
    content: `确定删除相册"${album.title}"吗？`,
    success: async ({ confirm }) => {
      if (confirm) {
        await coupleStore.removeAlbum(album.id)
        showSuccess('相册已删除')
      }
    },
  })
}

// 创建新相册
const handleCreateAlbum = async () => {
  if (!newAlbum.value.title) {
    return
  }

  await coupleStore.addAlbum({
    title: newAlbum.value.title,
    description: newAlbum.value.description || '',
    coverImage: newAlbum.value.coverImage || '', // 直接存 base64
  })

  // 重置表单
  newAlbum.value = {
    title: '',
    description: '',
    coverImage: '',
    photos: [],
  }

  showCreateDialog.value = false
  showSuccess('相册创建成功')
}

// 压缩（小程序端）
async function compressImageMp(path: string, quality = 70): Promise<string> {
  return await new Promise<string>((resolve, reject) => {
    uni.showLoading({ title: '压缩中...', mask: true })
    uni.compressImage({
      src: path,
      quality,
      success: (res) => {
        const out = (res as any).tempFilePath || path
        resolve(out)
      },
      fail: reject,
    })
  })
}

// 选择封面图片（读取为 base64 并保存到 coverImage）
const chooseCoverImage = async () => {
  try {
    const res: any = await uni.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
    })
    const tempPath = res?.tempFiles?.[0]?.tempFilePath
    if (!tempPath)
      return

    const compressed = await compressImageMp(tempPath, 70)
    const ext = compressed.substring(compressed.lastIndexOf('.') + 1).toLowerCase()
    const mime = ext === 'png' ? 'image/png' : ext === 'webp' ? 'image/webp' : 'image/jpeg'

    const fs = uni.getFileSystemManager()
    const base64 = await new Promise<string>((resolve, reject) => {
      fs.readFile({
        filePath: compressed,
        encoding: 'base64',
        success: (r: any) => resolve(r.data as string),
        fail: reject,
      })
    })
    newAlbum.value.coverImage = `data:${mime};base64,${base64}`
  }
  catch (err) {
    console.error('选择封面失败:', err)
  }
  finally {
    uni.hideLoading()
  }
}
</script>

<template>
  <view class="album-container">
    <!-- 统计信息 -->
    <view class="stats-header">
      <view class="stat-item">
        <view class="stat-number">
          {{ albums.length }}
        </view>
        <view class="stat-label">
          相册
        </view>
      </view>
      <view class="stat-item">
        <view class="stat-number">
          {{ totalPhotos }}
        </view>
        <view class="stat-label">
          照片
        </view>
      </view>
      <view class="stat-item">
        <wd-button
          type="primary"
          size="small"
          @click="showCreateDialog = true"
        >
          <wd-icon name="add" size="14px" />
          新建相册
        </wd-button>
      </view>
    </view>

    <!-- 相册网格 -->
    <view class="album-grid">
      <view
        v-for="album in albums"
        :key="album.id"
        class="album-item"
      >
        <view class="album-cover" @click="goToAlbumDetail(album)">
          <image
            :src="album.coverImage"
            class="cover-image"
            mode="aspectFill"
          />
          <view class="photo-count">
            <wd-icon name="picture" size="12px" />
            {{ album.photos.length }}
          </view>
        </view>
        <view class="album-info">
          <view class="album-header">
            <view class="album-title">
              {{ album.title }}
            </view>
            <wd-button size="small" plain @click="openAlbumActions(album)">
              更多
            </wd-button>
          </view>
          <view class="album-date">
            {{ dayjs(album.createdAt).format('YYYY年MM月') }}
          </view>
        </view>
      </view>
    </view>

    <!-- 最近照片 -->
    <view v-if="totalPhotos > 0" class="recent-photos">
      <view class="section-title">
        最近照片
      </view>
      <view class="photo-grid">
        <image
          v-for="photo in albums.flatMap(a => a.photos).slice(0, 6)"
          :key="photo.id"
          :src="photo.url"
          class="recent-photo"
          mode="aspectFill"
          @click="previewImage(photo.url, albums.flatMap(a => a.photos).map(p => p.url))"
        />
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="albums.length === 0" class="empty-state">
      <wd-icon name="picture" size="64px" color="#ccc" />
      <text class="empty-text">还没有相册，创建第一个相册吧！</text>
      <wd-button
        type="primary"
        style="margin-top: 16px;"
        @click="showCreateDialog = true"
      >
        创建相册
      </wd-button>
    </view>

    <!-- 创建相册弹窗 -->
    <wd-popup
      v-model="showCreateDialog"
      position="bottom"
      :safe-area-inset-bottom="true"
    >
      <view class="create-dialog">
        <view class="dialog-header">
          <view class="dialog-title">
            创建相册
          </view>
          <wd-icon name="close" @click="showCreateDialog = false" />
        </view>

        <view class="dialog-content">
          <!-- 封面选择 -->
          <view class="cover-selector" @click="chooseCoverImage">
            <image
              v-if="newAlbum.coverImage"
              :src="newAlbum.coverImage"
              class="cover-preview"
              mode="aspectFill"
            />
            <view v-else class="cover-placeholder">
              <wd-icon name="add" size="32px" color="#ccc" />
              <text>选择封面</text>
            </view>
          </view>

          <wd-cell-group>
            <wd-input
              v-model="newAlbum.title"
              label="相册名称"
              placeholder="请输入相册名称"
              required
            />
            <wd-input
              v-model="newAlbum.description"
              label="相册描述"
              placeholder="添加一些描述（可选）"
            />
          </wd-cell-group>
        </view>

        <view class="dialog-actions">
          <wd-button @click="showCreateDialog = false">
            取消
          </wd-button>
          <wd-button type="primary" @click="handleCreateAlbum">
            创建
          </wd-button>
        </view>
      </view>
    </wd-popup>

    <!-- 浮动创建按钮 -->
    <view class="fab-container">
      <view class="fab-button" @click="showCreateDialog = true">
        <wd-icon name="add" size="24px" color="white" />
      </view>
    </view>

    <wd-toast />
  </view>
</template>

<style lang="scss" scoped>
.album-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffb6c1 0%, #ffc0cb 50%, #ffb6c1 100%);
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image:
      radial-gradient(circle at 20% 30%, rgba(255, 182, 193, 0.3) 0%, transparent 50%),
      radial-gradient(circle at 80% 70%, rgba(255, 192, 203, 0.3) 0%, transparent 50%);
    pointer-events: none;
  }
}

.stats-header {
  background: white;
  padding: 20px 16px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  border-bottom: 1px solid #eee;

  .stat-item {
    text-align: center;

    .stat-number {
      font-size: 24px;
      font-weight: 600;
      color: #ff69b4;
      margin-bottom: 4px;
      text-shadow: 0 1px 3px rgba(255, 105, 180, 0.3);
    }

    .stat-label {
      font-size: 12px;
      color: #666;
    }
  }
}

.album-grid {
  padding: 16px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;

  .album-item {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .album-cover {
      position: relative;
      height: 120px;

      .cover-image {
        width: 100%;
        height: 100%;
      }

      .photo-count {
        position: absolute;
        top: 8px;
        right: 8px;
        background: rgba(0, 0, 0, 0.6);
        color: white;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 12px;
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }

    .album-info {
      padding: 12px;

      .album-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 4px;
      }

      .album-title {
        font-size: 14px;
        font-weight: 600;
        color: #333;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        flex: 1;
      }

      .album-date {
        font-size: 12px;
        color: #666;
      }
    }
  }
}

.recent-photos {
  margin: 0 16px 20px;
  background: white;
  border-radius: 12px;
  padding: 16px;

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
  }

  .photo-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;

    .recent-photo {
      width: 100%;
      height: 80px;
      border-radius: 8px;
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;

  .empty-text {
    margin-top: 16px;
    font-size: 14px;
    color: #999;
    text-align: center;
  }
}

.create-dialog {
  background: white;
  border-radius: 16px 16px 0 0;
  max-height: 80vh;

  .dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #eee;

    .dialog-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }

  .dialog-content {
    padding: 20px;

    .cover-selector {
      width: 100%;
      height: 120px;
      border: 2px dashed #ddd;
      border-radius: 8px;
      margin-bottom: 20px;
      overflow: hidden;

      .cover-preview {
        width: 100%;
        height: 100%;
      }

      .cover-placeholder {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #ccc;
        font-size: 14px;
        gap: 8px;
      }
    }
  }

  .dialog-actions {
    display: flex;
    gap: 12px;
    padding: 20px;
    border-top: 1px solid #eee;
  }
}

/* 浮动创建按钮 */
.fab-container {
  position: fixed;
  bottom: 80px; /* 在 tabBar 上方 */
  right: 20px;
  z-index: 1000;
}

.fab-button {
  width: 56px;
  height: 56px;
  border-radius: 28px;
  background: linear-gradient(135deg, #ff69b4, #ff1493);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow:
    0 8px 24px rgba(255, 105, 180, 0.4),
    0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  /* 禁用文字选择和点击高亮 */
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  outline: none;
  -webkit-tap-highlight-color: transparent;
  /* 添加呼吸发光效果 */
  animation: fab-glow 2s ease-in-out infinite alternate;

  &:hover,
  &:focus {
    background: linear-gradient(135deg, #ff1493, #dc143c);
    box-shadow:
      0 12px 32px rgba(255, 105, 180, 0.5),
      0 6px 16px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px) scale(1.05);
  }

  &:active {
    transform: translateY(0) scale(0.95);
    box-shadow:
      0 4px 12px rgba(255, 105, 180, 0.3),
      0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

@keyframes fab-glow {
  from {
    box-shadow:
      0 8px 24px rgba(255, 105, 180, 0.4),
      0 4px 12px rgba(0, 0, 0, 0.1);
  }
  to {
    box-shadow:
      0 8px 24px rgba(255, 105, 180, 0.4),
      0 4px 12px rgba(0, 0, 0, 0.1),
      0 0 20px rgba(255, 105, 180, 0.3);
  }
}
</style>
